/**
 * 打印
 */
const fs = require('fs');
const ipp = require('ipp');
const printList = require('../config/PrintList');

/**
 * 立即打印
 */

let print = async (ctx, next) => {
  const data = ctx.request.body;
  const file = ctx.request.files?.file;
  if(!file) {
    ctx.body = {
      code: 0,
      msg: '请选择打印文件',
      data: {}
    };
    return;
  }
  const printer = ipp.Printer(`http://${data.print}:631`);
  const fileData = await fs.readFileSync(file.filepath);
  if(fileData) {
    let printMsg = {
      'operation-attributes-tag': {
        'requesting-user-name': 'zfc-gx',
        'job-name': 'online-print',
        'document-format': 'application/pdf'
      },
      'job-attributes-tag': {
        'media': 'iso_a4_210x297mm',
        'copies': data.num,
        'print-color-mode': data.color == '1' ? 'auto' : 'monochrome',
        'sides': data.doublSided == '1' ? 'two-sided-long-edge' : 'one-sided', //  'sides-supported': [ 'one-sided', 'two-sided-short-edge', 'two-sided-long-edge' ],
      },
      data: fileData
    };
    if(file.mimetype.split('/')[0] == 'image') {
      printMsg['operation-attributes-tag']['document-format'] = file.mimetype;
    }
    if(file.mimetype.indexOf('vnd') > 0) {
      printMsg['operation-attributes-tag']['document-format'] = 'application/vnd.hp-PCLXL';
    }
    if(file.mimetype.indexOf('text') >=0 ) {
      printMsg['operation-attributes-tag']['document-format'] = 'text/plain';
    }
    const printRes = await new Promise((resolve) => {
      // printer.execute('Get-Printer-Attributes', null, function(err, res){
      //   console.log(res);
      // });
      printer.execute('Print-Job', printMsg, function(err, res){
        console.log(err, res);
        if(!err) resolve(res);
      });
    });
    if(printRes.statusCode == 'successful-ok') {
      ctx.body = {
        code: 0,
        msg: '成功',
        data: {}
      };
    } else if (printRes.statusCode == 'server-error-busy') {
      ctx.body = {
        code: -1,
        msg: '打印机正忙或打印机缺纸，请稍后再试',
        data: {
          file: file.originalFilename
        }
      };
    } else {
      ctx.body = {
        code: -1,
        msg: '打印错误',
        data: {}
      };
    }
  }
};


module.exports = {
  print
};